package gold.digger;

import gold.vo.ListNode;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC147 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public ListNode insertionSortList(ListNode head) {
            if (null == head || head.next == null) return head;
            ListNode sortedHead = new ListNode(head.val), cur = head.next;

            while (cur != null) {
                if (sortedHead.val > cur.val) {
                    int temp = cur.val;
                    cur.val = sortedHead.val;
                    sortedHead.val = temp;

                    ListNode sec = sortedHead.next, curDup = cur;
                    cur = cur.next;
                    sortedHead.next = curDup;
                    curDup.next = sec;
                } else {
                    ListNode sortedCur = sortedHead, sPrev = sortedHead;
                    while (sortedCur != null && sortedCur.val <= cur.val) {
                        sPrev = sortedCur;
                        sortedCur = sortedCur.next;
                    }

                    ListNode curDup = cur;
                    cur = cur.next;
                    sPrev.next = curDup;
                    curDup.next = sortedCur;
                }
            }

            return sortedHead;
        }

    }

    public void run() {
        Solution solution = new Solution();
        ListNode li = ListNode.createList("4->2->1->3");
        System.out.println(solution.insertionSortList(li));
    }

    public static void main(String[] args) throws Exception {
        LC147 an = new LC147();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
